/*
 * nlsync
 * Copyright (c) 2010 apechurin 
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO;

namespace nlsync.Resx
{
    /// <summary>
    /// A Resx based implementation of the IStringBundle interface.
    /// </summary>
    class ResxStringBundle : IStringBundle
    {
        #region StringEnumerator class

        /// <summary>
        /// The strings enumerator class.
        /// </summary>
        private class StringEnumerator : IEnumerator<IStringInfo>
        {
            #region Constructors

            /// <summary>
            /// Constructor.
            /// </summary>
            /// <param name="bundle">The parent bundle.</param>
            public StringEnumerator(ResxStringBundle bundle)
            {
                mBundle = bundle;
                Reset();
            }

            #endregion

            #region IEnumerator methods

            public IStringInfo Current
            {
                get
                {
                    XmlElement element = mEnum.Current as XmlElement;
                    return new ResxStringInfo(element, mBundle);
                }
            }

            object IEnumerator.Current
            {
                get
                {
                    return (this as IEnumerator<IStringInfo>).Current;
                }
            }

            public bool MoveNext()
            {
                while (mEnum.MoveNext())
                {
                    XmlElement element = mEnum.Current as XmlElement;
                    if (mBundle.IsStringInfo(element))
                        return true;
                }
                return false;
            }

            public void Reset()
            {
                mNodes = mBundle.mXmlDoc.SelectNodes("/root/data");
                mEnum = mNodes.GetEnumerator();
            }

            public void Dispose()
            {
            }

            #endregion

            #region Data fields

            private ResxStringBundle mBundle;
            private XmlNodeList mNodes;
            private IEnumerator mEnum;

            #endregion
        }

        #endregion

        #region Constructors

        /// <summary>
        /// Constructs a bundle with the specified name which is a relative
        /// Resx file path.
        /// </summary>
        /// <param name="name">The bundle name.</param>
        public ResxStringBundle(string name, ResxStringCatalog catalog) : 
            this(catalog)
        {
            // create a culture specific name of the bundle file, a bundle
            // name is a culture invariant - append a culture to the name
            string culture = catalog.Settings.Culture;
            if (culture != null && culture.Length > 0)
            {
                if (name.EndsWith(".resx", StringComparison.OrdinalIgnoreCase))
                {
                    name = name.Substring(0, name.Length - 4); // w/o `resx'
                    name += culture;
                    name += ".resx";
                }
            }

            // get a full path to the bundle file
            string rootFolder = catalog.RootFolder;
            if (rootFolder[rootFolder.Length - 1] != Path.DirectorySeparatorChar)
                rootFolder += Path.DirectorySeparatorChar;

            mFilename = rootFolder + name;
            mXmlDoc.Load(mFilename);

            Init();
        }

        private void Init()
        {
            mXmlRoot = mXmlDoc.DocumentElement;

            // get and check version of the Resx file
            XmlElement version = mXmlRoot.SelectSingleNode(
                "/root/resheader[@name='version']/value") as XmlElement;
            if (version == null)
                throw new Exception("Resx version attribute not found.");

            mVersion = new Version(version.InnerText);
            if (mVersion != Version13 && mVersion != Version20)
                throw new Exception("unsupported Resx version.");
        }

        /// <summary>
        /// Private constructor.
        /// </summary>
        private ResxStringBundle(ResxStringCatalog catalog)
        {
            mCatalog = catalog;
            mFilename = null;
            mModified = false;
            mXmlDoc = new XmlDocument();
            mXmlDoc.PreserveWhitespace = true;
        }

        /// <summary>
        /// The factory method. Creates a new object from an xml in a string.
        /// </summary>
        /// <param name="xml">The string with xml.</param>
        /// <param name="catalog">The catalog.</param>
        /// <returns>The created bundle.</returns>
        public static ResxStringBundle CreateFromString(string xml, ResxStringCatalog catalog)
        {
            ResxStringBundle bundle = new ResxStringBundle(catalog);
            bundle.mXmlDoc.LoadXml(xml);
            bundle.Init();

            return bundle;
        }

        #endregion

        #region IEnumerable methods

        public IEnumerator<IStringInfo> GetEnumerator()
        {
            return new StringEnumerator(this);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return new StringEnumerator(this);
        }

        #endregion

        #region IStringBundle methods

        public IStringInfo Find(string name)
        { 
            XmlNodeList nodes = mXmlDoc.SelectNodes("/root/data");
            foreach (XmlNode node in nodes)
            {
                XmlElement element = node as XmlElement;
                if (!IsStringInfo(element))
                    continue;

                string elementName = element.GetAttribute("name");
                if (name == elementName)
                    return new ResxStringInfo(element, this);
            }

            return null;
        }

        public IStringInfo Add(string name)
        { 
            XmlElement element = mXmlDoc.CreateElement("data");
            element.SetAttribute("name", name);
            mXmlRoot.AppendChild(element);
            Modified = true;
            return new ResxStringInfo(element, this);
        }

        public void Remove(IStringInfo str)
        {
            ResxStringInfo resxStr = str as ResxStringInfo;
            resxStr.Remove();
            Modified = true;
        }

        public bool IsCommentSupported
        {
            get
            {
                return mVersion.Major >= 2;
            }
        }

        public void Close()
        {
            if (mFilename != null && Modified)
                mXmlDoc.Save(mFilename);
        }

        #endregion

        #region Implementation

        /// <summary>
        /// Gets/sets the value of the Modified flag that shows is the document
        /// was modified or not.
        /// </summary>
        internal bool Modified
        {
            get
            {
                return mModified;
            }
            set
            {
                mModified = value;
            }
        }
        private bool mModified;

        /// <summary>
        /// Gets the Resx version.
        /// </summary>
        internal Version ResxVersion
        {
            get
            {
                return mVersion;
            }
        }
        private Version mVersion;

        /// <summary>
        /// Gets the catalog.
        /// </summary>
        internal ResxStringCatalog Catalog
        {
            get
            {
                return mCatalog;
            }
        }
        private ResxStringCatalog mCatalog;

        /// <summary>
        /// Returns true if a specified element is a string data element.
        /// </summary>
        /// <param name="element">The element.</param>
        private bool IsStringInfo(XmlElement element)
        {
            return !element.HasAttribute("type")
                && !element.HasAttribute("mimetype");
        }

        #endregion

        #region Data fields

        internal static readonly Version Version13 = new Version("1.3");
        internal static readonly Version Version20 = new Version("2.0");

        private XmlDocument mXmlDoc;
        private XmlNode mXmlRoot;
        private string mFilename;

        #endregion
    }
}
